/****************************************************************************************
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.transference.TransferenceVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQuerySceneOrderAttrService;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAccountDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosCustomerDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccCommonAttrVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TransferInfoVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.AssemblyAttrDtoUtils;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.AreaNameCache;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.ExtOrderInfoCache;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.IPersonAttrDealService;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <Description> 过户业务模块组件
 *
 * @author wei.yanhong
 * @version 1.0<br>
 * @see com.iwhalecloud.bss.kite.web.service.accept.handler.module <br>
 * @since R9.0<br>
 */
@Service
public class LocalTransferencePositionCustModuleHandler extends AbstractModuleHandler {

    @Autowired
    ILocalQuerySceneOrderAttrService querySceneOrderAttrService;

    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Autowired
    private IPersonAttrDealService personAttrDealService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {
        TransferInfoVO transferInfoVO = this.getTransferDisplayInfoAttrs(context.getAcceptRequest().getSceneInstId());

        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
        if (KiteListUtils.isNotEmpty(kiteProdInsts)) {
            kiteProdInsts.forEach(kiteProdInst -> {
                transferInfoVO.setProdInstId(kiteProdInst.getProdInstId());
                transferInfoVO.setCustId(context.getAcceptRequest().getCustId());
            });
        }

        List<TransferenceVO> transferenceVOList = new ArrayList<>();
        transferenceVOList.add(transferInfoVO);
        operateSceneInstService.putExtParameter(sceneInstId, "transferProdInst", transferenceVOList);

        SceneNewOfferSeneVO seneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        seneVO.setTransferInfo(transferInfoVO);

        return Collections.singletonList(transferInfoVO);
    }

    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        TransferInfoVO transferInfoVO = this.getTransferDisplayInfoAttrs(context.getAcceptRequest().getSceneInstId());
        List<CommonAttrVO> cuccAttrList = new ArrayList<>();
        List<CommonAttrVO> transferDisplayInfoAttrs = transferInfoVO.getTransferInfoAttr();
        if (KiteListUtils.isNotEmpty(transferDisplayInfoAttrs)) {
            //设置预览模式
            transferDisplayInfoAttrs.forEach((attr) -> {
                if ("provinceCode".equals(attr.getFieldName()) || "eparchyCode".equals(attr.getFieldName())) {
                    attr.setValueDesc(LocalAttrHelper.getRegionName(attr.getValue()));
                }
                attr.setAttrValueTypeId("TT");
            });

            cuccAttrList = this
                .getCuccCommonAttrVOList(transferDisplayInfoAttrs, context.getAcceptRequest().getSceneInstId());
        }

        transferInfoVO.setTransferInfoAttr(cuccAttrList);
        SceneNewOfferSeneVO sceneAccountInfoVo = (SceneNewOfferSeneVO) context.getSceneVo();
        sceneAccountInfoVo.setTransferInfo(transferInfoVO);

        return Collections.singletonList(transferInfoVO);
    }

    private List<CommonAttrVO> getCuccCommonAttrVOList(List<CommonAttrVO> transferDisplayInfoAttrs,
        String sceneInstId) {
        List<CommonAttrVO> cuccAttrList = new ArrayList<>();
        transferDisplayInfoAttrs.forEach(commonAttrVO -> {
            CuccCommonAttrVO cuccCommonAttrVO = new CuccCommonAttrVO();
            // 处理过户变更的信息
            this.dealTransCustOldValues(cuccCommonAttrVO, commonAttrVO, sceneInstId);
            cuccAttrList.add(cuccCommonAttrVO);

        });
        return cuccAttrList;
    }

    private void dealTransCustOldValues(CuccCommonAttrVO cuccCommonAttrVO, CommonAttrVO commonAttrVO,
        String sceneInstId) {
        KiteBeanUtils.copyProperties(commonAttrVO, cuccCommonAttrVO);
        KitePosDTO kitePosDTO = ExtOrderInfoCache.get(sceneInstId);
        if (Objects.nonNull(kitePosDTO)) {
            KitePosCustomerDTO cuccCustInfo = kitePosDTO.getCustomer();
            if ("custName".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(cuccCustInfo.getName(), commonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(cuccCustInfo.getName());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("groupId".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(cuccCustInfo.getGroupId(), commonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(cuccCustInfo.getGroupId());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("custId".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(cuccCustInfo.getCustId(), commonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(cuccCustInfo.getCustId());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("location".equals(commonAttrVO.getFieldName())) {
                StringBuilder valueDesc = new StringBuilder();
                valueDesc.append(
                    AreaNameCache.get(cuccCustInfo.getEparchyProvince() + "-" + cuccCustInfo.getEparchyProvince()))
                    .append("-")
                    .append(AreaNameCache.get(cuccCustInfo.getEparchyProvince() + "-" + cuccCustInfo.getEparchyCity()))
                    .append("-")
                    .append(AreaNameCache.get(cuccCustInfo.getEparchyProvince() + "-" + cuccCustInfo.getEparchyArea()));
                cuccCommonAttrVO.setValue(valueDesc.toString());
                cuccCommonAttrVO.setValueDesc(valueDesc.toString());
                if (!KiteStringUtils.isEqual(valueDesc.toString(), cuccCommonAttrVO.getValue())) {
                    cuccCommonAttrVO.setOldValue(valueDesc.toString());
                    cuccCommonAttrVO.setChangeFlag(true);
                }
                return;
            }

        }
        //        Object account = querySceneInstService.getExtParameter(sceneInstId).get(sceneInstId + "_transNewAccountDTO");
        List<KitePosAccountDTO> kitePosAccountDTOList = kitePosDTO.getAccounts();
        if (KiteListUtils.isNotEmpty(kitePosAccountDTOList)) {
            KitePosAccountDTO accountDto = kitePosAccountDTOList.get(0);
            if ("is_trans_acct".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getIsDefault(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setChangeFlag(true);
                cuccCommonAttrVO.setOldValue(accountDto.getIsDefault());
                String valueDesc = cuccCommonAttrVO.getValue();
                String value = cuccCommonAttrVO.getValue();
                if (!KiteStringUtils.isEmpty(cuccCommonAttrVO.getValue()) && KeyConsts.DROPDOWN
                    .equals(commonAttrVO.getAttrValueTypeId())) {
                    valueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttrVO.getAttrId(), value))
                        .map((attrValue) -> attrValue.getAttrValueDesc()).orElse("");
                }
                cuccCommonAttrVO.setValueDesc(valueDesc);
                return;
            }

            if ("acctName".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getName(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(accountDto.getName());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("payMode".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getPayMode(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(accountDto.getPayMode());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("acctContractCode".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getAcctContractCode(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(accountDto.getAcctContractCode());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("eparchyCode".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getEparchyCode(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(LocalAttrHelper.getRegionName(accountDto.getEparchyCode()));
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("openDate".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getOpenDate(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(accountDto.getOpenDate());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("provinceCode".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getProvinceCode(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(LocalAttrHelper.getRegionName(accountDto.getProvinceCode()));
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("provinceAcctId".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getProvinceAcctId(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(accountDto.getProvinceAcctId());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else if ("cbssAcctId".equals(commonAttrVO.getFieldName()) && !KiteStringUtils
                .isEqual(accountDto.getCbssId(), cuccCommonAttrVO.getValue())) {
                cuccCommonAttrVO.setOldValue(accountDto.getCbssId());
                cuccCommonAttrVO.setChangeFlag(true);
                return;
            }
            else {
                cuccCommonAttrVO.setOldValue(cuccCommonAttrVO.getValue());
                return;
            }
        }

    }

    public TransferInfoVO getTransferDisplayInfoAttrs(String sceneInstId) {

        TransferInfoVO transferInfoVO = new TransferInfoVO();

        //只查showType为D的
        List<InstAttrDTO> attrConfigs = queryScenePersonService
            .listKiteConfigAttrs(sceneInstId, LocalKeyConsts.TRANSFER_DISPLAY_OBJECT_TYPE).getResultObject().stream()
            .filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_D.equals(instAttrDTO.getShowType()))
            .collect(Collectors.toList());

        if (KiteListUtils.isEmpty(attrConfigs)) {
            return null;
        }

        List<CommonAttrVO> commonAttrList = AssemblyAttrDtoUtils.assemblyVO(attrConfigs);
        transferInfoVO.setTransferInfoAttr(commonAttrList);
        personAttrDealService.initAttrList(commonAttrList);
        return transferInfoVO;
    }
}
